package wangjg.commons.bean;

import java.lang.reflect.Field;

/**
 * 
 * @author wangjg
 *
 */
public class Fill {

	public static void deepFill(Object bean) throws Exception {
		Class<?> c = bean.getClass();
		for (Class<?>cc=c; cc!=Object.class; cc=cc.getSuperclass()) {
			Field[] fields= cc.getDeclaredFields();
			fill(bean, fields);
		}
	}
	
	public static void fill(Object bean) throws Exception {
		Field[] fields= bean.getClass().getDeclaredFields();
		fill(bean, fields);
	}
	
	private static void fill(Object bean, Field[] fields) throws Exception {
		for(int i=0;i<fields.length;i++){
			Field field = fields[i];
			field.setAccessible(true);
			Class<?> fieldCls=field.getType();
			if(field.get(bean)==null){
				if(Number.class.isAssignableFrom(fieldCls)){
					if(fieldCls.equals(Byte.class)){
						field.set(bean, (byte)0);
					}else if(fieldCls.equals(Short.class)){
						field.set(bean, (short)0);
					}else if(fieldCls.equals(Integer.class)){
						field.set(bean, 0);
					}else if(fieldCls.equals(Long.class)){
						field.set(bean, 0L);
					}else if(fieldCls.equals(Float.class)){
						field.set(bean, 0f);
					}else if(fieldCls.equals(Double.class)){
						field.set(bean, 0d);
					}
				}else{
					field.set(bean, fieldCls.newInstance());
				}
			}
		}
	}

}
